<template>
  <div>

    <el-button type="primary" size="mini" style="width: 60px;margin-left: 20px;margin-top: 20px" @click="closePage">返回
    </el-button>
    <el-row :gutter="13">
      <p></p>
      <el-form ref="elForm" :rules="rules" :model="formData" size="small" label-width="100px">
        <el-col :span="6">
          <el-form-item label="通知名称:" prop="title">
            <el-input v-model="formData.title" placeholder="请输入通知名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="发布日期:" prop="publishTime">
            <el-date-picker type="date" v-model="formData.publishTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            :style="{width: '100%'}" :picker-options="pickerTime" @change="changeTime"
                            placeholder="点击选择发布日期"
                            clearable></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="通知内容:" prop="content">
            <vue-editor useCustomImageHandler placeholder="请输入内容" @image-added="handleImageAdded"
                        v-model="formData.content"></vue-editor>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否回复:" prop="answerType">
            <el-radio-group v-model="formData.answerType" size="medium" @change="changeAnswerType">
              <el-radio v-for="(item, index) in answerOptions" :key="index" :label="item.value"
                        :disabled="item.disabled">{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="5" v-if="formData.answerType==='1'">
          <el-form-item label="回复截止:" prop="deadlineTime">
            <el-date-picker type="date" v-model="formData.deadlineTime" format="yyyy-MM-dd"
                            :picker-options="pickerTime1" value-format="yyyy-MM-dd" :style="{width: '100%'}"
                            placeholder="请选择回复截止日期"
                            clearable>
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="附件:" prop="uploadFileList">
            <el-upload style="display: flex;align-items: center" ref="upload" :file-list="formData.uploadFileList"
                       :auto-upload="false" :action="uploadTheAddress" :on-success="handleFileSuccess"
                       :headers="Authorization"
                       :on-error="handleFileError" :on-change="handleChange" :on-remove="handleRemove"
                       :on-exceed="handleExceed"
                       :before-upload="uploadInspect" :limit="1">
              <el-button size="small" type="primary" icon="el-icon-upload">选择文件</el-button>
            </el-upload>
            <div style="margin-top: 10px" class="el-upload__tip">提示：只能上传一个不超过50MB的文件</div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="通知人员:" prop="staff">
            <el-checkbox-group v-model="formData.staff" size="medium" @change="schoolChange">
              <el-checkbox v-for="(item, index) in schoolOptions" :key="index" :label="item.value"
                           :disabled="item.disabled">{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
            <el-form-item prop="schoolsKey">
              <el-transfer ref="transfer" @change="chooseSchool" v-model="formData.schoolsKey" :data="schoolList"
                           :titles="titles"></el-transfer>
            </el-form-item>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm1">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import {
  listSchool
} from "@/api/patrol/school"
import {
  parseTime
} from "@/utils/ruoyi";
import {
  getToken
} from "@/utils/auth";
import {
  VueEditor
} from "vue2-editor";
import axios from "axios";

import {
  getNotification,
  addNotification,
  updateNotification
} from "@/api/patrol/notification";
import {
  getNotifination_school
} from "@/api/patrol/notifination_user";

export default {
  components: {
    VueEditor
  },
  props: [],
  data() {

    return {
      pickerTime: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的;
        }
      },
      pickerTime1: {},
      titles: ['可选择', '已选择'],
      number: 0,
      Authorization: {
        Authorization: getToken()
      },
      notifination_userList: [],

      notificationId: null,
      formData: {
        //通知标题
        title: '',
        //发布时间
        publishTime: parseTime(new Date(), "{y}-{m}-{d}"),
        //通知内容
        content: '',
        //是否需要回复
        answerType: '1',
        //回复截止时间
        deadlineTime: '',
        //文件上传路径
        uploadFileList: [],
        //选择的学校类型
        staff: [],
        // 选择的学校
        schoolsKey: [],
      },

      rules: {
        title: [{
          required: true,
          message: '请输入通知名称',
          trigger: 'blur'
        }],
        publishTime: [{
          required: true,
          message: '请选择发布日期'
        }],
        content: [{
          required: true,
          message: '请输入通知内容'
        }],
        deadlineTime: [{
          required: true,
          message: '请选择回复截止时间'
        }],
        uploadFileList: [],
        schoolsKey: [{
          required: true,
          message: '请选择需要通知的学校',
          trigger: 'blur'
        }]
      },
      uploadTheAddress: process.env.VUE_APP_BASE_API + "/common/upload",
      answerOptions: [{
        "label": "是",
        "value": '1'
      }, {
        "label": "否",
        "value": '0'
      }],

      schoolOptions: [{
        "label": "幼儿园",
        "value": 0,
        disabled: false
      }, {
        "label": "小学",
        "value": 1,
        disabled: false
      }, {
        "label": "中学",
        "value": 2,
        disabled: false
      }, {
        "label": "高中",
        "value": 3,
        disabled: false
      }, {
        "label": "九年一贯制",
        "value": 4,
        disabled: false
      }, {
        "label": "特殊教育",
        "value": 5,
        disabled: false
      }],

      // 查询学校参数
      querySchoolParams: {
        pageNum: 1,
        name: null,
        type: null,
        nature: null,
        userId: null,
      },
      schoolList: [],
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loading = true;
    this.notificationId = this.$route.query.notifyId;
    listSchool(this.querySchoolParams).then(result => {
      let data = result.rows
      for (let i = 0; i < data.length; i++) {
        this.schoolList.push({
          key: data[i].id,
          label: data[i].name,
          type: data[i].type - 0
        })
      }

      let map = new Map();
      for (const scItem of this.schoolList) {
        map.set(scItem.type, 0)
      }

      for (const scOption of this.schoolOptions) {
        if (map.get(scOption.value) !== 0) {
          scOption.disabled = true
        }
      }

      setTimeout(function () {
        document.getElementsByClassName('el-checkbox-group el-transfer-panel__list').forEach(v => {
          v.getElementsByClassName("el-checkbox__label").forEach(v => {
            v.setAttribute('title', v.textContent)
          })
        })
      }, 500);


    })
  },
  mounted() {
    this.$set(this.pickerTime1, "disabledDate", (time) => {
      return time.getTime() < new Date(this.formData.publishTime).getTime();
    })

    if (this.notificationId !== "false") {

      getNotification(this.notificationId).then(res => {
        let data = res.data;
        this.formData.title = data.title;
        this.formData.content = data.content;
        this.formData.publishTime = new Date(this.formData.publishTime);
        this.formData.answerType = data.answerType;
        if (data.fileUrl) {
          this.formData.uploadFileList = [{
            name: "附件",
            url: data.fileUrl
          }];
        } else {
          this.formData.uploadFileList = [];
        }
        this.loading = false;
      });

      setTimeout(() => {
        //查询通知的学校
        getNotifination_school(this.notificationId).then(res => {
          this.formData.schoolsKey = res
          //处理学校类型联动问题
          this.chooseSchool()
        })
      }, 500)

    }

  },
  methods: {
    //改变回复截止时间
    changeTime() {
      this.formData.deadlineTime = ""
    },
    //选择学校
    chooseSchool() {
      let old = JSON.parse(JSON.stringify(this.schoolList))
      let left = []
      for (let item of old) {
        if (this.formData.schoolsKey.indexOf(item.key) === -1) {
          left.push(item)
        }
      }

      this.formData.staff = []
      for (let item of this.schoolOptions.filter(e => e.disabled === false)) {
        let find = left.find(e => {
          return e.type === item.value
        })
        if (find === undefined) {
          this.formData.staff.push(item.value)
        }
      }
      setTimeout(function () {
        document.getElementsByClassName('el-checkbox-group el-transfer-panel__list').forEach(v => {
          v.getElementsByClassName("el-checkbox__label").forEach(v => {
            v.setAttribute('title', v.textContent)
          })
        })
      }, 500);
    },

    // 修改学校类别把学校加入临时学校list
    schoolChange(vale) {
      this.formData.schoolsKey = []
      for (let item of vale) {
        let filter = this.schoolList.filter(e => {
          return e.type === item
        })
        for (let i = 0; i < filter.length; i++) {
          if (this.formData.schoolsKey.indexOf(filter[i].key) === -1) {
            this.formData.schoolsKey.push(filter[i].key)
          }
        }
      }

    },
    changeAnswerType() {
      if (this.formData.answerType === '1') {
        this.rules.deadlineTime = [{
          required: true,
          message: '请选择回复截止时间'
        }]
      } else {
        this.rules.deadlineTime = []
        this.formData.deadlineTime = ""
      }
    },

    submitForm1() {
      if (this.number > 0) {
        this.$refs.upload.submit();
      } else {
        this.submitForm();
      }
    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.notificationId !== "false") {
          this.$set(this.formData, "id", this.notificationId)
          this.$set(this.formData, "status", '0')
          updateNotification(this.formData).then(res => {
            this.msgSuccess("编辑成功")
            if (res.code === 200) {
              this.$tab.closeOpenPage({
                path: "/system/notification"
              }).then(() => {
                this.$tab.refreshPage()
              });
            }
          })
        } else {
          addNotification(this.formData).then(res => {
            this.msgSuccess("新增成功")
            if (res.code === 200) {
              this.$tab.closeOpenPage({
                path: "/system/notification"
              }).then(() => {
                this.$tab.refreshPage()
              });
            }
          })
        }
      })
    },
    handleFileSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$set(this.formData, "fileUrl", response.fileName)
        this.submitForm();
      }
    },
    handleFileError(error, file, fileList) {
      this.msgError("文件上传失败，请重试")
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，已选择了 ${fileList.length} 个文件`);
    },
    handleChange(files, fileList) {
      this.number = fileList.length
    },
    handleRemove(files, fileList) {
      this.number = fileList.length
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    uploadInspect(file) {
      let isRightSize = file.size / 1024 / 1024 <= 50
      if (!isRightSize) {
        this.$message.error('文件大小超过 50MB,请重新上传！')
      }
      return isRightSize
    },
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      //formDta是个对象，用来模拟表单的
      let formData = new FormData()
      formData.append('file', file)
      //上传图片并回显
      axios({
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        method: 'POST',
        headers: this.Authorization,
        data: formData
      }).then(res => {
        //这两行是关键代码了。在鼠标位置插入图片，数据存的是url
        console.log(res)
        Editor.insertEmbed(cursorLocation, 'image', res.data.url)
        resetUploader()
      }).catch(err => {
        console.log(err)
      })
    },
    //关闭页面
    closePage() {
      this.$store.dispatch('tagsView/delView', this.$route)
      // this.$router.go(-1)
      this.$tab.openPage("通知公告", "/system/notification");
    }
  }
}

</script>
<style scoped>
.el-upload__tip {
  line-height: 1.2;
  margin-top: 0;
}

::v-deep .el-upload-list,
.el-upload-list--text {
  display: flex;
  align-items: center;
}

::v-deep .el-upload-list__item:first-child {
  margin-top: 0;
}

::v-deep .el-transfer-panel {
  width: 300px;
}

::v-deep .el-upload-list__item,
.is-ready {
  margin-left: 10px;
}

::v-deep.el-transfer :nth-child(3) div {
  border: 1px solid #00B3A8;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header {
  border: 1px solid #00B3A8;
  background: #00B3A8;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label {
  color: white;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label span {
  color: white;
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label::before {
  content: "常规";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before {
  content: "标题1";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before {
  content: "标题2";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before {
  content: "标题3";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before {
  content: "标题4";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before {
  content: "标题5";
}

::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before,
::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before {
  content: "标题6";
}

</style>
